package com.qf.web;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.qf.config.AlipayConfig;
import com.qf.pojo.*;
import com.qf.service.OrderService;
import com.qf.service.impl.OrderServiceImpl;
import com.qf.utils.UUIDUtils;
import com.sun.org.apache.xpath.internal.operations.Or;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

/**
 * 订单模块
 */
@WebServlet("/order")
public class OrderServlet extends BaseServlet {

    /**
     * 生成订单
     * @param request
     * @param response
     */
    public void addOrder(HttpServletRequest request,HttpServletResponse response) throws Exception {
        System.out.println("进入生成订单的方法了...");
        //1)从session中获取user
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            //没登录过,请求转发到/jsp/login.jsp
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
            return;
        }


        //2)用户登录过了
        //封装订单
        Order order = new Order() ;
        //订单编号:UUID生成的
        order.setOid(UUIDUtils.getId());
        //下订单时间
        Date date = new Date() ; //创建当前系统日期 ,精确到毫秒
        //java.util.Date--- //public Instant toInstant():将当前系统时间的毫秒值----即时时间点

        //LocalDateTime
        //public static LocalDateTime ofInstant(Instant instant, ZoneId zone)
        //参数1:instant - 即时创建日期时间 (在时间线上的瞬间点)
        //参数2:默认时区   ---->public static ZoneId systemDefault() :获取默认时区

        LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
        order.setOrdertime(localDateTime);
        //从session中获取购物车
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        //订单封装它的总计金额
        order.setTotal(cart.getTotalMoney());
        //state,支付状态,address,name,tetetphone:先不给值

        //获取所有的购物车项
        OrderItem orderItem =null ;
      //  Collection<CartItem> items = cart.getItems();
        for(CartItem cartItem :cart.getItems()){
            orderItem =  new OrderItem() ;
            //订单项OrderItem 里面的数据都来与购物车项
            orderItem.setItemid(UUIDUtils.getId()); //订单项id
            orderItem.setProduct(cartItem.getProduct());//订单项中的包含商品---购物车项的商品
            orderItem.setCount(cartItem.getCount()) ; //订单项中的商品数量---购物车商品的数量
            orderItem.setSubtotal(cartItem.getSubTotal()) ;//订单项中的小计金额---购物车商品的小计金额

            //这个订单项属于哪个订单的
            orderItem.setOrder(order);
            //订单封装多个订单项
            order.getItems().add(orderItem) ;
        }



        //订单属于哪个用户的
        order.setUser(user);


        //调用订单业务接口
        OrderService orderService = new OrderServiceImpl() ;
        orderService.add(order) ;

        //将订单实体放在request域中
        request.setAttribute("bean",order) ;

        //从session中将购物车删除
        request.getSession().removeAttribute("cart");
        //请求转发到订单详情中
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);




    }

    /**
     * 查询订单列表
     * @param request  请求对象
     * @param response 响应对象
     */
    public void findOrderByPage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //判断用户是登录过
        User user = (User) request.getSession().getAttribute("user");
        if(user==null){
            //错误提示
            request.setAttribute("msg","您尚未登录,请先<a href='http://localhost:8080/maven_study_02_war/user?methodName=loginUI'>登录</a>");
            request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response) ;
            return;
        }


        //接收两个参数
        //currentPage=1&pageSize=3
        String curPage = request.getParameter("currentPage");
        String pSize = request.getParameter("pageSize");
        //转int
        int currentPage= Integer.parseInt(curPage) ;
        int pageSize = Integer.parseInt(pSize) ;

        //调用 订单的业务接口
        OrderService orderService = new OrderServiceImpl() ;
        PageBean<Order> pb = orderService.getOderByPage(currentPage,pageSize,user.getUid()) ;
        System.out.println(pb);


        //将pageBean对象存储在request域中
        request.setAttribute("pb",pb);
        //请求转发到/jsp/order_list.jsp
        request.getRequestDispatcher("/jsp/order_list.jsp").forward(request,response);
    }


    /**
     *
     * 通过订单编号获取订单实体
     * @param request
     * @param response
     */
    public void findOrderById(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //${pageContext.request.contextPath}/order?methodName=findOrderById&oid=${o.oid}
        //接收前台提交的参数
        String oid = request.getParameter("oid");
        //调用订单业务接口
        OrderService orderService = new OrderServiceImpl() ;
        Order order  = orderService.getOrderById(oid );

        //将order存储在request域中
        request.setAttribute("bean",order) ;
        request.getRequestDispatcher("/jsp/order_info.jsp").forward(request,response);

    }

    /**
     * 订单支付
     * @param request
     * @param response
     */
    public void pay(HttpServletRequest request,HttpServletResponse response){

        //接收参数
        //订单编号
        //地址/收货人/电话
        String oid = request.getParameter("oid");
        String address = request.getParameter("address");
        String name = request.getParameter("name");
        String telephone = request.getParameter("telephone");
        Order order = new Order() ;
        order.setAddress(address);
        order.setTelephone(telephone);

        order.setName(name);

        //调用业务接口更新订单
        OrderService orderService = new OrderServiceImpl() ;
        orderService.update(order) ;





        //支付宝的客户端的配置
        try {



            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    AlipayConfig.gatewayUrl,
                    AlipayConfig.app_id,
                    AlipayConfig.merchant_private_key,
                    "json",
                    AlipayConfig.charset, AlipayConfig.alipay_public_key,
                    AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

            String orderNO = request.getParameter("oid");
            //调用业务层接口
            //通过订单编号获取订单
            Order orderObj = orderService.getOrderById(orderNO);


            //			//商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no =  orderObj.getOid() ;
//			//付款金额，必填
            Double total = orderObj.getTotal();
            String total_amount = String.valueOf(total) ;

//			//订单名称，必填
            String subject = "商品支付";

            //商品描述，可空
            String body = "您有什么建议";



            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                    + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //        + "\"total_amount\":\""+ total_amount +"\","
            //        + "\"subject\":\""+ subject +"\","
            //        + "\"body\":\""+ body +"\","
            //        + "\"timeout_express\":\"10m\","
            //        + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
            AlipayTradePagePayResponse alipayResponse = null;
            try {
                alipayResponse=alipayClient.pageExecute(alipayRequest);
                System.out.println(alipayResponse.getBody());
                System.out.println(alipayResponse.getMsg());
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            response.setContentType("text/html;charset=UTF-8"); //设置编码
            response.getWriter().write(alipayResponse.getBody());  //将支付宝支付的首页显示给浏览器

            return   ;

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
